package com.android.shangtaowang.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.android.shangtaowang.R;
import com.android.shangtaowang.activity.mine.TransparentActivity;
import com.android.shangtaowang.app.BaseActivity;
import com.android.shangtaowang.model.detail.BargainOrderData;
import com.android.shangtaowang.model.detail.BargainShareData;
import com.android.shangtaowang.utils.ConstantsUrl;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.google.gson.Gson;
import com.zhy.http.okhttp.cookie.store.PersistentCookieStore;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Cookie;

/**
 * 跳转到砍价模块
 */

public class BargainWeb extends BaseActivity {

    @BindView(R.id.webView)
    BridgeWebView webView;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.main_top_share)
    ImageView shareImgV;
    private BargainWeb mcontext;
    private String url;
    private PersistentCookieStore cookieStore;
    private BargainShareData shareData;
    private boolean isDouble;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bargainweb);
        ButterKnife.bind(this);
        mcontext = BargainWeb.this;
        url = ConstantsUrl.baseDomain + "bargain/index";
        cookieStore = new PersistentCookieStore(mcontext);
        initTitle(0, getString(R.string.app_name));
        initUI();
    }

    @Override
    protected void onStart() {
        super.onStart();
        isDouble = false;
    }

    private void initUI() {

            /* 设置支持Js,必须设置的,不然网页基本上不能看 */
//        WebSettings settings = webView.getSettings();
//        settings.setJavaScriptEnabled(true);
            /* 设置缓存模式,我这里使用的默认,不做多讲解 */
//        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
            /* 设置为true表示支持使用js打开新的窗口 */
//        settings.setJavaScriptCanOpenWindowsAutomatically(true);
            /* 大部分网页需要自己保存一些数据,这个时候就的设置下面这个属性 */
//        settings.setDomStorageEnabled(true);
        webView.setWebViewClient(new MyWebViewClient(webView));
        webView.setDefaultHandler(new myHadlerCallBack());
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    progress.setVisibility(View.GONE);
                }
            }
        });
        synCookies(mcontext, url);
        webView.loadUrl(url);
        //必须和js同名函数，注册具体执行函数，类似java实现类。
        webView.registerHandler("bargainingShare", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                // 这是html返回给java的数据
                shareData = new Gson().fromJson(data, BargainShareData.class);
            }

        });

        webView.registerHandler("bargainingOrder", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                if(!isDouble){
                    isDouble = true;
                    // 这是html返回给java的数据
                    BargainOrderData orderData = new Gson().fromJson(data, BargainOrderData.class);
                    Intent intent = new Intent(mcontext, PayActivity.class);
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_NUM, "1");
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_TYPEID, 0);
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_LOG_ID, orderData.getLog_id());
                    startActivityForResult(intent,1);
                }
            }
        });
    }

    /**
     * 自定义回调
     */
    class myHadlerCallBack extends DefaultHandler {

        @Override
        public void handler(String data, CallBackFunction function) {
            if(function != null){

//                Toast.makeText(mcontext, data, Toast.LENGTH_SHORT).show();
            }
        }
    }

    //cookie同步
    @SuppressWarnings("deprecation")
    public void synCookies(Context context, String url) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
//      cookieManager.removeSessionCookie();// 移除

        cookieManager.removeAllCookie();
        //   String[] cookie = mCookieStr.split(";");

        //     Cookie[] cookie  = CookieUtil.getCookies().toArray(
// new Cookie[CookieUtil.getCookies().size()]);

        List<Cookie> cookies = cookieStore.getCookies();

        StringBuffer sb = new StringBuffer();


        for (Cookie cookie : cookies) {

            String cookieName = cookie.name();
            String cookieValue = cookie.value();
            if (!TextUtils.isEmpty(cookieName)
                    && !TextUtils.isEmpty(cookieValue)) {
                sb.append(cookieName + "=");
                sb.append(cookieValue + ";");
            }
        }


        String[] cookie = sb.toString().split(";");
        for (int i = 0; i < cookie.length; i++) {
            Log.d("cookie[i]", cookie[i]);
            cookieManager.setCookie(url, cookie[i]);// cookies是在HttpClient中获得的cookie
        }


        CookieSyncManager.getInstance().sync();
    }

    class MyWebViewClient extends BridgeWebViewClient {
        public MyWebViewClient(BridgeWebView webView) {
            super(webView);
        }
        //拦截网址
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            String orderUrl = ConstantsUrl.baseDomain + "flow/team";
            if (url.startsWith(orderUrl)) {
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            String shareUrl = ConstantsUrl.baseDomain + "bargain/show";
            if (url.startsWith(shareUrl)) {
                shareImgV.setVisibility(View.VISIBLE);
            } else {
                shareImgV.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        webBack();
    }

    private void webBack() {
        String backUrl = webView.getUrl();
        if (TextUtils.isEmpty(backUrl) || backUrl.equals(url)) {
            mcontext.finish();
        } else {
            webView.goBack();
        }
    }

    @OnClick({R.id.main_top_share})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_top_share:
                if(shareData != null && !TextUtils.isEmpty(shareData.getUrl())){
                    Intent share = new Intent(mcontext, TransparentActivity.class);
                    share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_TYPE, 1);
                    share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_TITLE, shareData.getTitle());
                    share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_CONTENT, shareData.getDesc());
                    share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_IMAGEURL, shareData.getShare_logo());
                    share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_LINK, shareData.getUrl());
                    mcontext.startActivity(share);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 1){
            webBack();
        }
    }
}
